package com.example.zluserservice.aspect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @Author zhenliu（孙凌岳）
 * @Description 切面打印所有Service中公共方法的业务日志
 * @Date 2025/6/22 12:50
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class BusinessLogAspect {

    //匹配service包下面所有public方法
    @Around("execution(public * com.example.zluserservice.service.impl..*(..))")
    public Object logBusinessMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().toShortString();

        //打印方法入参，避免过大日志可只打印部分或敏感字段遮蔽
        try {
            log.info("[业务日志] 方法开始：{}，参数：{}", methodName, JSONUtil.toJsonStr(joinPoint.getArgs()));
        } catch (Exception e) {
            log.warn("[业务日志] 方法入参序列化异常", e);
        }

        Object result;
        try {
            result = joinPoint.proceed();
            try {
                log.info("[业务日志] 方法成功：{}，返回值：{}", methodName, JSONUtil.toJsonStr(result));
            } catch (Exception e) {
                log.warn("[业务日志] 方法返回值序列化异常", e);
            }
        } catch (Throwable e) {
            log.error("[业务日志] 方法异常：{}，异常信息：{}", methodName, e.getMessage(), e);
            throw e;
        }

        return result;
    }
}